<template>
  <div class="select-group" style="width: 240px;margin-bottom: 10px;display: inherit;">
    <select-group v-model:gn="selectedGN" placeholder="选择分组" @on-select="handleSelectGroup" />
  </div>
  <div v-if="selectedGN">
    <el-row style="margin-bottom: 10px;">
      <el-col :span="24">
        <el-row v-if="swSlProductsShow" class="service-box">
          <el-form ref="formRef" label-width="50px">
            <el-form-item label="开关" prop="sw">
              <el-switch v-model="sw" :active-value = "1" :inactive-value = "0" />
            </el-form-item>
            <el-form-item label="亮度" prop="sl">
              <el-slider v-model="sl" :max="100" :min="0" />
            </el-form-item>
          </el-form>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>
  
<script>
import SelectGroup from '@/components/YtSelect/select-group.vue'
import { getDeviceGroupsList } from '@/views/setting/device/api/devices.api'
import { ElMessage } from 'element-plus'
// 引入公共方法获取设备属性、判断是否为灯控设备和网关
import { getDeviceProperties, isLightController } from '@/utils/deviceUtils'

export default defineComponent({
  name: 'GroupAction',
  props: {
    services: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    SelectGroup,
  },
  data() {
    return {
      showGroupSelector: false,
      selectedPk: '', // 旧的产品key
      newSelectedPk: '', // 新的产品key
      selectedGN: '', // 分组名
      selectedGId: '', // 分组id
      properties: [],
      servicesRef: this.services,
      propertiesList: [],
      servicesList: [],
      swSlProductsShow: false, // 选择设备后service-box显示为开关亮度的组件
      sw: 0,
      sl: 0,
      swName: '',
      slName: '',
    }
  },
  emits: ['update:services'],
  mounted() {
    console.log('GroupAction mounted', this.services)
    this.servicesRef = this.services
    this.services.map((m, i) => {
      if (m.group && i === 0) {
        const firstObj = m.group ? m.group.split('/') : ''
        if (firstObj) {
          this.selectedPk = firstObj[0] || '' // 旧的产品key
          this.selectedGId = firstObj[1] === '#' ? '' : firstObj[1] // 分组id
          
          // 保存inputData以便稍后处理
          const inputDataToProcess = m.inputData && m.inputData.length > 0 ? [...m.inputData] : null;
          
          // 如果有分组ID，查询分组详情
          if (this.selectedGId) {
            // 查询分组详情，并在回调中处理inputData
            this.getDeviceGroupDetails(this.selectedGId, inputDataToProcess)
          }
        }
      }
    })
  },
  methods: {
    openGroupSelector() {
      this.showGroupSelector = !this.showGroupSelector
    },
    // 获取分组详情(分组id)
    getDeviceGroupDetails(groupId, inputData = null) {
      if (!groupId) return

      getDeviceGroupsList({
        id: groupId
      }).then(res => {
        // 如果分组信息存在，则显示分组名与开关亮度控件
        if (res.data && res.data.rows && res.data.rows.length > 0) {
          this.selectedGN = res.data.rows[0].name // 分组名
          
          // 如果有产品信息，更新产品Key
          if (res.data.rows[0].product && res.data.rows[0].product.productKey) {
            this.newSelectedPk = res.data.rows[0].product.productKey // 新的产品key

            // 如果新旧产品key相同，则显示开关亮度控件
            // 如果产品类型在支持列表中，则显示开关亮度控件
            if (this.selectedPk == this.newSelectedPk && isLightController(this.newSelectedPk)) {
              this.swSlProductsShow = true
              
              // 设置对应的属性名称
              const { swName, slName } = getDeviceProperties(this.newSelectedPk)
              this.swName = swName
              this.slName = slName
              
              // 处理之前保存的inputData
              if (inputData && inputData.length > 0) {
                inputData.forEach(input => {
                  if (input.identifier === this.swName) {
                    this.sw = input.value
                  } else if (input.identifier === this.slName) {
                    this.sl = input.value
                  }
                })
              }
              
              // 调用updateServices确保服务数据更新
              this.$nextTick(() => {
                this.updateServices()
              })
            } else {
              this.swSlProductsShow = false
            }
          } else {
            this.swSlProductsShow = false
          }
        } else {
          // 如果没有分组信息，则显示返回的分组id
          this.selectedGN = this.selectedGId
          this.swSlProductsShow = false
        }
      })
    },
    // 选择完设备根据设备的group.product.productKey显示不同service-box组件
    handleSelectGroup(group) {
      // 判断是否有产品信息和设备数量
      //if (this.swSlProducts.includes(this.selectedPk) && (group.product || group.deviceQty > 0)) {
      if (group.product || group.deviceQty > 0) {
        // 更新选中的分组信息
        this.selectedPk = group.product?.productKey || ''
        this.selectedGN = group.name
        this.selectedGId = group.id
        
        // 根据产品类型设置是否显示开关亮度控件
        if (isLightController(this.selectedPk)) {
          this.swSlProductsShow = true

          const { swName, slName } = getDeviceProperties(this.selectedPk)
          this.swName = swName
          this.slName = slName
        } else {
          this.swSlProductsShow = false
        }

        // 更新设备信息到services
        this.updateServices()
      } else {
        return ElMessage.warning('该分组下无设备信息')
      }
    },
    // 更新services数据
    updateServices() {
      if (!this.selectedPk || !this.selectedGId) return
      
      // 构建group字符串
      const groupPath = `${this.selectedPk}/${this.selectedGId}`
      
      // 构建输入数据
      const inputData = []
      
      // 仅当显示开关亮度控件时添加这些参数
      if (this.swSlProductsShow && this.swName && this.slName) {
        inputData.push({
          identifier: this.swName,
          value: this.sw
        })
        inputData.push({
          identifier: this.slName,
          value: this.sl
        })
      }
      
      // 如果services为空，创建一个新的，否则更新现有的
      if (this.servicesRef.length === 0) {
        this.servicesRef.push({
          group: groupPath,
          identifier: 'set',  // 固定为set
          inputData: inputData
        })
      } else {
        // 更新现有的service
        this.servicesRef[0].group = groupPath
        this.servicesRef[0].identifier = 'set'
        this.servicesRef[0].inputData = inputData
      }
      
      // 通知父组件services已更新
      this.$emit('update:services', this.servicesRef)
    },
  },
  watch: {
    // 监听开关和亮度值的变化
    sw() {
      this.updateServices()
    },
    sl() {
      this.updateServices()
    }
  }
})
</script>

<style scoped>
.service-box {
  border: 1px solid #ddd;
  border-radius: 3px;
  padding: 5px 5px;
  background-color: #eee;
}
.el-form {
  width: 70%;
}
.el-slider {
  padding: 10px 20px 10px 10px;
}
</style>
  